package com.xmwzw.catpu;

import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.CompoundButton;

import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.xmwzw.catpu.bean.CollectionEvent;
import com.xmwzw.catpu.bean.SoftBean;
import com.xmwzw.catpu.databinding.ActivitySoftDetailBinding;
import com.xmwzw.catpu.db.SoftModel;
import com.xmwzw.catpu.db.SoftModel_Table;
import com.xmwzw.catpu.http.BaseRequest;
import com.xmwzw.catpu.http.bean.DetailBean;
import com.xmwzw.catpu.http.listener.DetailListener;
import com.xmwzw.catpu.util.ActivityManagerUtils;
import com.xmwzw.catpu.util.Constant;
import com.xmwzw.catpu.viewmodel.DownloadViewModel;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

/**
 * @author : wangzw
 * @date : 20-4-3下午4:00
 * @desc :
 */
public class SoftDetailActivity extends BaseActivity {
    private ActivitySoftDetailBinding detailBinding;
    private String url;
    private SoftBean softBean;
    private DownloadViewModel viewModel;
    private MyHandler handler;
    public boolean isCollection;
    private SoftModel softModel;

    @Override
    public int getLayoutId() {
        return R.layout.activity_soft_detail;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        detailBinding = getBaseViewBinding();
        detailBinding.setClick(new Click());
        softBean = getIntent().getParcelableExtra(Constant.KEY_SOFT_BEAN);
        detailBinding.setModel(viewModel = new DownloadViewModel());
        detailBinding.setBean(softBean);
        viewModel.setShowProgressBar(false);

        url = softBean.down_url;
        softModel = SQLite.select().from(SoftModel.class).where(SoftModel_Table.id.eq(softBean.id)).querySingle();

        isCollection = softModel.isCollect;

        detailBinding.cbCollection.setChecked(isCollection);
        handler = new MyHandler(this);
        getData(Integer.valueOf(softBean.id));

    }


    private void getData(int id) {
        BaseRequest.getInstance().getDetail(id, new DetailListener() {
            @Override
            public void getDetail(DetailBean detailBean) {
                Message message = handler.obtainMessage();
                message.what = 1;
                message.obj = detailBean.getContent();
                handler.sendMessage(message);
            }
        });
    }

    public class Click {

        public void copy() {
            //获取剪贴板管理器：
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);

            ClipData mClipData = ClipData.newPlainText("Label", url);

            cm.setPrimaryClip(mClipData);

            showToast("已复制到剪贴板");
        }

        public void download() {
            if (Constant.IS_NORMAL_LOGIN) {
                showDialog();
            } else {

                detailBinding.ll.setVisibility(View.VISIBLE);
            }
//            showToast("开始下载");
//            viewModel.setShowProgressBar(true);
//            DownloadUtils.getInstance().downloadAPK(url, new DownloadListener() {
//                @Override
//                public void onProgress(int progress) {
//                    Log.d("", "onProgress: " + progress);
//                    viewModel.setProgress(progress);
//                }
//
//                @Override
//                public void onFinish() {
//                    viewModel.setShowProgressBar(false);
//                    DownloadUtils.getInstance().installAPK();
//                }
//            });

        }

        public void back() {
            finish();
        }

        public void onCheck(CompoundButton buttonView, boolean isChecked) {
            softModel.isCollect = isChecked;
            softModel.update();
            SoftModel softModel1 = SQLite.select().from(SoftModel.class).where(SoftModel_Table.id.eq(softBean.id)).querySingle();
            Log.d("tag", "onCheck: " + softModel1.isCollect);
            EventBus.getDefault().post(new CollectionEvent());
        }


    }

    private static class MyHandler extends Handler {
        WeakReference<SoftDetailActivity> weakReference;

        public MyHandler(SoftDetailActivity activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    weakReference.get().loadWeb((String) msg.obj);
                    break;

            }
        }
    }

    private void loadWeb(String html) {
        Log.d("", "loadWeb: " + html);
        WebSettings webSettings = detailBinding.webview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);

        webSettings.setBuiltInZoomControls(true);
        //防止中文乱码
        webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setTextSize(WebSettings.TextSize.LARGEST);

        detailBinding.webview.addJavascriptInterface(new JavascriptInterface(), "imagelistner");


        detailBinding.webview.setWebViewClient(new WebViewClient() {
            //覆写shouldOverrideUrlLoading实现内部显示网页
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO 自动生成的方法存根
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                addImageClickListener();
            }
        });
        detailBinding.webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {

                if (newProgress == 100) {
                    detailBinding.progressBar1.setVisibility(View.GONE);//加载完网页进度条消失
                } else {
                    detailBinding.progressBar1.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    detailBinding.progressBar1.setProgress(newProgress);//设置进度值
                }

            }
        });
        detailBinding.webview.loadData(Html.fromHtml(html).toString(), "text/html", "UTF-8");


    }

    // 注入js函数监听
    private void addImageClickListener() {
        //遍历页面中所有img的节点，因为节点里面的图片的url即objs[i].src，保存所有图片的src.
        //为每个图片设置点击事件，objs[i].onclick
        detailBinding.webview.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName(\"img\"); " +
                "for(var i=0;i<objs.length;i++) " +
                "{" +
                "window.imagelistner.readImageUrl(objs[i].src); " +
                " objs[i].onclick=function() " +
                " { " +
                " window.imagelistner.openImage(this.src); " +
                " } " +
                "}" +
                "})()");
    }

    private ArrayList<String> images = new ArrayList<>();

    // js通信接口
    public class JavascriptInterface {

        @android.webkit.JavascriptInterface
        public void readImageUrl(String img) {  //把所有图片的url保存在ArrayList<String>中
            images.add(img);
        }

        @android.webkit.JavascriptInterface //对于targetSdkVersion>=17的，要加这个声明
        public void openImage(String clickImg) {
            Log.d("tag", "openImage: " + clickImg);

            Intent intent = new Intent(SoftDetailActivity.this, PhotoDetailActivity.class);
            intent.putExtra("url",clickImg);
            startActivity(intent);

        }
    }


    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("游客无法查看下载连接,\n是否进行登录?")
                .setTitle("提示")
                .setPositiveButton("登录", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        ActivityManagerUtils.getInstance().finishAllActivity();
                        startActivity(new Intent(SoftDetailActivity.this, LoginActivity.class));
                        finish();
                    }
                })
                .setNeutralButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                }).show();

    }

}
